<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <!-- 新 Bootstrap 核心 CSS 文件 -->
  <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
  <!-- 可选的Bootstrap主题文件（一般不用引入） -->
  <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap-theme.min.css">
  <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
  <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
  <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  <script src="http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col-lg-4">
      <h5>文件名称</h5>
      <ol id="list">
      </ol>
    </div>
    <div class="col-lg-8">
      <form>
        <textarea class="form-control" id="content" rows="3"></textarea><br>
        <input type="text" class="form-control hidden" id="newtitle" placeholder="Text input"><br>
        <input type="button" id="btn"  class="btn btn-default" disabled value="save"/>
        <input name="filename" id="filename" type="hidden"/>
      </form>
    </div>
  </div>
</div>
<script>
  $(function(){

      $.get(
        "/list.php",
        function(r){
          if(r.code){}
          else{
            var files = r.data.files;
            for(var i in files){
              $("<li>").appendTo($("#list")).html(files[i]);
            }
          }
        },
        "json"
      );

    $("#list").on("click","li",function(){
      var _self = $(this);
      $("#btn").prop("disabled",true);
      $.get(
        "/read.php",
        {"filename":_self.text()},
        function(r){
          if(r.code){
            alert("内容输出错误");
          }
          else{
            $("#content").val(r.data.content);
            $("#filename").val(_self.text());
            var idx = $("#content").val().split("\n").length;
            $("#content").attr("rows",idx);
            $("#btn").prop("disabled",false);
          }
        },
        "json"
      );
    });
    $("#btn").on("click",function(){
      $("#btn").prop("disabled",true);
      var title;
      if( $("#filename").val()== ""){
        $(".hidden").removeClass("hidden");
        title = $("#newtitle").val();
      }
      else{
        title = $("#filename").val();
      }
      var _self = $(this);
      $.post(
        "/write.php",
        {"filename": title,"content":$("#content").val()},
        function(r){
          if(r.code){
            alert("保存失败");
          }
          else{
            alert("保存成功了");
          }
          $("#btn").prop("disabled",false);
        },
        "json"
      );
    });
    $("#content").on("keyup",function(){
      var idx = $("#content").val().split("\n").length;
      $("#content").attr("rows",idx);
      if( $("#filename").val()== ""){
        $(".hidden").removeClass("hidden");
        $("#btn").prop("disabled",false);
      }
    });

  })
</script>
</body>
</html>